/**
 * desc quest13.js
 * 使用framebufferObject
 */

var gl = null;
var d  = {};

var g_cubeInfo;
var g_LightCubeInfo;
var g_boxInfo;


let floorSize = 500;
let g_planeInfo = null;

var lightCubeSize = 10
var lightCubePos = [10, 400, 120];
var cameraPos = [30, 90, 500]

var boxSize = 60;
var boxPos = [-0, 0, -0];

var ambientLight = [0.6, 0.6, 0.6];
var pointlight = [0,1,0];
// 
var shininess = 150;
var innerLimit = 10;
var outerLimit = 20;
var lightRotationX = 30;
var lightRotationY = 0;
var lightDirection = [0.5, 0.5, 1]; // this is computed in updateScene

let g_angle1 = 120;
let g_angle2 = 220;
let g_angle_step = 1;

let step1;
let step2;   

let OFFSCREEN_WIDTH = 0,OFFSCREEN_HEIGHT = 0;

function main() {
    console.log("main");

    gl = initGL("canvas_1");
    if(!gl){
        return
    }

    OFFSCREEN_WIDTH = gl.canvasWidth /2;
    OFFSCREEN_HEIGHT = gl.canvasHeight /2;

    console.log("OFFSCREEN_WIDTH",OFFSCREEN_WIDTH);
    console.log("OFFSCREEN_HEIGHT",OFFSCREEN_HEIGHT);

    

    initUI();
    initFramebufferObject();
    setupMatrix();
    setupCubeData();
    setupPlaneData();
    loadTexture(gl, 'resources/container.jpg', function (texture) {
        d.cubeTexture = texture
    });
    // --画图
    loadTexture(gl, 'resources/concrete1.jpg', function (texture) {        
        d.texture = texture;        
    });
    

    // drawScene();
    var tick = function(){
        if(d.cubeTexture && d.texture){
            drawScene();
        }
        requestAnimationFrame(tick);
    }
    tick();
}


function initFramebufferObject() {
    
    console.log("initFramebufferObject() -> ");

    // let framebuffer,texture,depthBuffer;
    let framebuffer = gl.createFramebuffer();
    if(!framebuffer) {
        console.log("Failed to create frame buffer object");
        return;
    }
    let texture = gl.createTexture();
    if(!texture){
        console.log("Failed to create texture object");
        return;
    }

    gl.bindTexture(gl.TEXTURE_2D,texture);    
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, OFFSCREEN_WIDTH,OFFSCREEN_HEIGHT,0,gl.RGBA,gl.UNSIGNED_BYTE,null);    
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    framebuffer.texture = texture;

    let depthBuffer = gl.createRenderbuffer();
    if(!depthBuffer){
        console.log("Failed to create renderbuffer object");
        return;
    }
    gl.bindRenderbuffer(gl.RENDERBUFFER,depthBuffer);
    gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,OFFSCREEN_WIDTH,OFFSCREEN_HEIGHT);
    
    gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);
    gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);
    gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,depthBuffer);

    

    let e = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if(e !== gl.FRAMEBUFFER_COMPLETE ){
        console.log("Frame buffer object is inComplete:" +e.toString());
        return;
    }
    gl.bindFramebuffer(gl.FRAMEBUFFER,null);
    gl.bindTexture(gl.TEXTURE_2D,null);
    gl.bindRenderbuffer(gl.RENDERBUFFER,null);

 
    d.fbo = framebuffer;
    return framebuffer;


    
}

// 



function setupCubeData() {

    let positions = [
        //前面
        -1.0, 0.0, 1.0,
        1.0, 0.0, 1.0,
        1.0, 2.0, 1.0,
        -1.0, 2.0, 1.0,

        //后 
        -1.0, 0.0, -1.0,
        -1.0, 2.0, -1.0,
        1.0, 2.0, -1.0,
        1.0, 0.0, -1.0,
        

        //上
        -1.0, 2.0, -1.0,
        -1.0, 2.0, 1.0,
        1.0, 2.0, 1.0,
        1.0, 2.0, -1.0,

        //下
        -1.0, 0.0, -1.0,
        1.0, 0.0, -1.0,
        1.0, 0.0, 1.0,
        -1.0, 0.0, 1.0,

        //左
        -1.0, 0.0, -1.0,
        -1.0, 0.0, 1.0,
        -1.0, 2.0, 1.0,
        -1.0, 2.0, -1.0,

        //右边
        1.0, 0.0, -1.0,
        1.0, 2.0, -1.0,
        1.0, 2.0, 1.0,
        1.0, 0.0, 1.0,
    ];

    const faceColors = [
        [1.0, 0.0, 0.0, 1.0], // Front face: white
        [1.0, 0.0, 0.0, 1.0], // Back face: red
        [0.0, 1.0, 0.0, 1.0], // Top face: green
        [0.0, 0.0, 1.0, 1.0], // Bottom face: blue
        [1.0, 1.0, 0.0, 1.0], // Right face: yellow
        [1.0, 0.0, 1.0, 1.0], // Left face: purple
    ];

    let colors = [];
    for (var j = 0; j < faceColors.length; ++j) {
        const c = faceColors[j];
        colors = colors.concat(c, c, c, c);
    }


    // 法线
    let normals = [
        // Front
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,

        // Back
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,

        // Top
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,

        // Bottom
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,

        // Left
        -1.0, 0.0, 0.0,
        -1.0, 0.0, 0.0,
        -1.0, 0.0, 0.0,
        -1.0, 0.0, 0.0,
        // Right
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,


    ];
    // 索引
    let indices = [
        0, 1, 2, 0, 2, 3,
        4, 5, 6, 4, 6, 7,
        8, 9, 10, 8, 10, 11,
        12, 13, 14, 12, 14, 15,
        16, 17, 18, 16, 18, 19,
        20, 21, 22, 20, 22, 23,
    ];

    // 纹理
    const textureIndies = [
        //front
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,

        //back
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,

        //left
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,
        //right
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,
        //bottom
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,
        //top
        0.0, 0.0,
        1.0, 0.0,
        1.0, 1.0,
        0.0, 1.0,
    ];

    d.cubeData = {
        positions: positions,
        colors: colors,
        indices: indices,
        textureIndies: textureIndies,
        normals: normals,
    };
}

function setupPlaneData() {

  let positions = [
    -0.5,-0.5, 0.0, 
    0.5, -0.5, 0.0, 
    0.5, 0.5, 0.0,        
    -0.5,0.5, 0.0    // v0-v1-v2-v3
  ];

  // Texture coordinates
  let textureIndies = [ 
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
  ];

  // Indices of the vertices
  
  d.planeData = {
        positions: positions,        
        // indices: indices,
        textureIndies: textureIndies,        
    };

}
function initUI() {
    console.log("initUI() -> ");

    webglLessonsUI.setupSlider("#cam_x", {
        value: cameraPos[0],
        slide: function(event,ui) {
            cameraPos[0] = ui.value;
            // drawScene()
        },
        
        min: -360,
        max: 360,
    });

    webglLessonsUI.setupSlider("#cam_y", {
        value: cameraPos[1],
        slide: function(event,ui) {
            cameraPos[1] = ui.value;
            // drawScene()
        },
        
        min: -120,
        max: 360,
    });

    webglLessonsUI.setupSlider("#cam_z", {
        value: cameraPos[2],
        slide: function(event,ui) {
            cameraPos[2] = ui.value;
            // drawScene()
        },
        
        min: -500,
        max: 500,
    });

    webglLessonsUI.setupSlider("#speed", {
        value: g_angle_step,
        slide: function(event,ui) {
            g_angle_step = ui.value;            
        },
        
        min: 0,
        max: 10,
    });
}

//
function setupMatrix() {
    console.log("setupMatrix -> ");

   

    let viewProjMatrix = new Matrix4();
    viewProjMatrix.setPerspective(50,gl.canvas.width/gl.canvas.height,1.0,1000.0);
    d.projectionMatrix = new Matrix4(viewProjMatrix);

    // viewProjMatrix.lookAt(20,10,30,0,0,0,0,1,0);
    // d.viewProjMatrix = viewProjMatrix;
    d.viewMatrix = new Matrix4();
   

    d.modelMatrix = new Matrix4();
    d.mvpMatrix = new Matrix4();
    d.normalMatrix = new Matrix4();
    
    gl.enable(gl.DEPTH_TEST);
    // gl.depthFunc(gl.LEQUAL);
    // gl.clearColor(0.6,0.6,0.6,1.0);
}

function updateViewMatrix(index) {
    var target = [0, 0, 0];
    var up = [0, 1, 0];

    let camPos;
    if (index == 1) {
        camPos =  [0, 0, 300]
    }
    else if(index == 2){
        camPos =  [0, 00, -300];
    }
    else if (index == 3){
        camPos = [300, 0, 00];
    }
    else if (index == 4){
        camPos = [-300, 0, 00];
    }

    d.viewMatrix.setLookAt(...camPos,...target,...up);
}

// 画box
function drawBox(boxSize, boxPos,angle){
    console.log("drawBox -> ", boxSize, boxPos);

    angle = angle || 0;
    if (!g_boxInfo) {
        g_boxInfo = {
            buffers: initBuffer(),
            programInfo: initProgramInfo(),
        }
    }

    function initBuffer() {
        let positions = d.cubeData.positions
        let textureIndies = d.cubeData.textureIndies;
        let colors = d.cubeData.colors;
        let indices = d.cubeData.indices;
        let normals = d.cubeData.normals;

        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);


        const texcoordBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureIndies), gl.STATIC_DRAW);

        const colorBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);


        const normalBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);


        const indexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

        return {
            positions: positionBuffer,
            textureIndies: texcoordBuffer,
            colors: colorBuffer,
            indices: indexBuffer,
            normals: normalBuffer,
        };
    }

    function initProgramInfo() {

        let vsSource = `
        attribute vec4 aVertexPosition;
        attribute vec2 aTextureCoord;
        attribute vec3 aNormal; //法线

        uniform vec3 uLightWorldPosition;
        uniform vec3 uViewWorldPosition;
        uniform mat4 uProjectionMatrix;  
        uniform mat4 uViewMatrix;
        uniform mat4 uModelMatrix;  
        uniform mat4 uNormalMatrix; 

        uniform vec3 uAmbientLight;    //环境光颜色

        varying vec2 vTextureCoord;
        varying vec3 v_normal;
        varying vec3 v_surfaceToLight;
        varying vec3 v_surfaceToView;
        varying vec3 v_ambient;

        void main() {
            mat4 mvpMatrix = uProjectionMatrix  *uViewMatrix * uModelMatrix;
            gl_Position = mvpMatrix * aVertexPosition;
            vTextureCoord = aTextureCoord;
            v_normal = mat3(uNormalMatrix) * aNormal;
            vec3 surfaceWorldPosition = (uModelMatrix * aVertexPosition).xyz;
            v_surfaceToLight = uLightWorldPosition - surfaceWorldPosition;
            v_surfaceToView  = uViewWorldPosition - surfaceWorldPosition;
            v_ambient = uAmbientLight;
        }`;


        let fsSource = `
        #ifdef GL_ES
        precision mediump float;
        #endif
        
       
        uniform float u_shininess;
        uniform vec3  u_lightDirection;
        uniform float u_innerLimit;          // in dot space
        uniform float u_outerLimit;          // in dot space
        uniform sampler2D uSampler;

        // varying vec4 vColor;
        varying vec2 vTextureCoord;
        varying vec3 v_normal;        
        varying vec3 v_surfaceToLight;
        varying vec3 v_surfaceToView;
        varying vec3 v_ambient;

        void main() {            
            vec4 texColor = texture2D(uSampler, vTextureCoord);
            vec3 normal = normalize(v_normal);
            vec3 surfaceToLightDirection = normalize(v_surfaceToLight);
            vec3 surfaceToViewDirection = normalize(v_surfaceToView);
            vec3 halfVector = normalize(surfaceToLightDirection + surfaceToViewDirection);

            float dotFromDirection = dot(surfaceToLightDirection,-u_lightDirection);
            float inLight = smoothstep(u_outerLimit, u_innerLimit, dotFromDirection);
            float light = inLight * dot(normal, surfaceToLightDirection);
            float specular = inLight * pow(dot(normal, halfVector), u_shininess);

            vec3 diffuse = texColor.rgb * light;  // + specular;
            vec3 ambient = v_ambient * texColor.rgb ;
            gl_FragColor = vec4(diffuse + ambient, texColor.a);
            // gl_FragColor = vec4(1.0,1.0,0.6,1.0);
        }`;

        const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
        return {
            program: shaderProgram,
            attribLocations: {
                vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
                textureCoord: gl.getAttribLocation(shaderProgram, "aTextureCoord"),
                normalPosition: gl.getAttribLocation(shaderProgram, "aNormal")
            },
            uniformLocations: {
                projectionMatrix: gl.getUniformLocation(shaderProgram, "uProjectionMatrix"),
                lightPosition: gl.getUniformLocation(shaderProgram, 'uLightWorldPosition'),
                cameraPosition: gl.getUniformLocation(shaderProgram, 'uViewWorldPosition'),
                viewMatrix: gl.getUniformLocation(shaderProgram, "uViewMatrix"),
                modelMatrix: gl.getUniformLocation(shaderProgram, "uModelMatrix"),
                normalMatrix: gl.getUniformLocation(shaderProgram, 'uNormalMatrix'),
                ambientLight: gl.getUniformLocation(shaderProgram, 'uAmbientLight'),
                sampler: gl.getUniformLocation(shaderProgram, "uSamper"),
                shininess: gl.getUniformLocation(shaderProgram, "u_shininess"),
                lightDirection: gl.getUniformLocation(shaderProgram, "u_lightDirection"),
                innerLimit: gl.getUniformLocation(shaderProgram, "u_innerLimit"),
                outerLimit: gl.getUniformLocation(shaderProgram, "u_outerLimit"),
            },
        };
    }

    function render() {
        console.log("render -> drawBox");

        const scaleFactorX = boxSize[0] / 2.0;
        const scaleFactorY = boxSize[1] / 2.0;
        const scaleFactorZ = boxSize[2] / 2.0;

        pushMatrix(d.modelMatrix)

        // d.modelMatrix
        // d.modelMatrix.setRotate(angle,1,0,0).translate(...boxPos).scale(scaleFactorX,scaleFactorY,scaleFactorZ);
        d.modelMatrix.scale(scaleFactorX,scaleFactorY,scaleFactorZ);;
        const buffers = g_boxInfo.buffers;
        const programInfo = g_boxInfo.programInfo;
        gl.useProgram(programInfo.program);

        // 模型矩阵的逆矩阵
        let normalMatrix = new Matrix4();
        normalMatrix.setInverseOf(d.modelMatrix);
        normalMatrix.transpose();

        gl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix, false, d.projectionMatrix.elements);
        gl.uniformMatrix4fv(programInfo.uniformLocations.viewMatrix, false,  d.viewMatrix.elements);
        gl.uniformMatrix4fv(programInfo.uniformLocations.modelMatrix, false, d.modelMatrix.elements);
        gl.uniformMatrix4fv(programInfo.uniformLocations.normalMatrix, false, normalMatrix.elements);

        // 设置灯光的位置
        gl.uniform3fv(programInfo.uniformLocations.lightPosition, lightCubePos);

        // lookat 位置
        gl.uniform3fv(programInfo.uniformLocations.cameraPosition, cameraPos);

        // ambientColor
        gl.uniform3fv(programInfo.uniformLocations.ambientLight, ambientLight)

        // shiness
        gl.uniform1f(programInfo.uniformLocations.shininess, shininess);

        {


            let lmat2 = m4.lookAt(lightCubePos, [0, 0, 0], [0, 1, 0]);
            lmat2 = m4.multiply(m4.xRotation(degToRad(lightRotationX)), lmat2); // 绕着x轴旋转
            lmat2 = m4.multiply(m4.yRotation(degToRad(lightRotationY)), lmat2); //绕着Y轴旋转
            // console.log("lmat2",lmat2);
            lightDirection = [-lmat2[8], -lmat2[9], -lmat2[10]];
            console.log("direction", lightDirection);

            let matrixRotation = new Matrix4();
            matrixRotation.rotate(lightRotationY, 0, 1, 0).rotate(lightRotationX, 1, 0, 0)
            let lightDir = new Vector3(lightCubePos)

            let dir = matrixRotation.multiplyVector3(lightDir).normalize();
            lightDirection = [-dir.elements[0], -dir.elements[1], -dir.elements[2]];
            console.log("direction", lightDirection);
            // 
        }

        // 灯光位置
        gl.uniform3fv(programInfo.uniformLocations.lightDirection, lightDirection);

        // 内径
        gl.uniform1f(programInfo.uniformLocations.innerLimit, Math.cos(degToRad(innerLimit)));

        // 外径
        gl.uniform1f(programInfo.uniformLocations.outerLimit, Math.cos(degToRad(outerLimit)));


        // // 设置位置属性
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.positions);
        gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);

        //normal
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normals);
        gl.vertexAttribPointer(programInfo.attribLocations.normalPosition, 3, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(programInfo.attribLocations.normalPosition);

        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureIndies);
        gl.vertexAttribPointer(programInfo.attribLocations.textureCoord, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);

        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, d.cubeTexture);
        gl.uniform1i(programInfo.uniformLocations.sampler, 0);

        // // indies
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
        gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);


        d.modelMatrix = popMatrix();
    }

    render();
}

// 画Frambuffer
function drawPlane(texture,index){

    g_planeInfo = g_planeInfo || {
        buffers: initBuffer(),
        programInfo: initProgramInfo(),
    }


    function initBuffer() {
       
        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(d.planeData.positions), gl.STATIC_DRAW);


        const texcoordBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,  texcoordBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(d.planeData.textureIndies), gl.STATIC_DRAW);

        return {
            positions: positionBuffer,
            textureIndies: texcoordBuffer,            
        }
    }
    function initProgramInfo() {

        let vsSource = `
            attribute vec4 aVertexPosition;
            attribute vec2 aTextureCoord;
            uniform mat4 uMvpMatrix;
            varying vec2 vTextureCoord;     
            void main() {
                gl_Position = uMvpMatrix * aVertexPosition;
                vTextureCoord = aTextureCoord;                
            }`;

        let fsSource = `            
            precision mediump float;            
            uniform sampler2D uSampler;
            varying vec2 vTextureCoord;            
            void main() {            
                vec4 texColor = texture2D(uSampler, vTextureCoord);                
                gl_FragColor = texColor;
            }`;

        const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
        return {
            program: shaderProgram,
            attribLocations: {
                vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
                textureCoord: gl.getAttribLocation(shaderProgram, "aTextureCoord"),                
            },
            uniformLocations: {
                mvpMatrix: gl.getUniformLocation(shaderProgram, "uMvpMatrix"),
                sampler: gl.getUniformLocation(shaderProgram, "uSamper"),
            },
        };
    }


    const buffers = g_planeInfo.buffers;
    const programInfo = g_planeInfo.programInfo;

    // 画立方体
    gl.useProgram(programInfo.program);

    let modelMatrix = new Matrix4();

    if(index == 1)
        modelMatrix.setTranslate(-0.5, 0.5, 0);
    else if(index == 2)
        modelMatrix.setTranslate(0.5, 0.5, 0);
    else if(index == 3)
        modelMatrix.setTranslate(0.5, -0.5, 0);
    else if (index == 4)
        modelMatrix.setTranslate(-0.5, -0.5, 0);
    
    // modelMatrix.rotate(20.0, 1.0, 0.0, 0.0);    

    let  viewProjMatrix = new Matrix4();   // Prepare view projection matrix for FBO
    viewProjMatrix.setPerspective(50.0, OFFSCREEN_HEIGHT/OFFSCREEN_HEIGHT, 1.0, 1000.0);
    // viewProjMatrix.lookAt(0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    var target = [0, 0, 0];
    var up = [0, 1, 0];
    viewProjMatrix.lookAt(0.0, 0.0, 2.0,...target,...up);

    d.mvpMatrix.set(viewProjMatrix);
    d.mvpMatrix.multiply(modelMatrix);

    gl.uniformMatrix4fv(programInfo.uniformLocations.mvpMatrix, false, d.mvpMatrix.elements);
    gl.uniform1i(programInfo.uniformLocations.sampler, 0);

    // // 设置位置属性
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.positions);
    gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);



    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureIndies);
    gl.vertexAttribPointer(programInfo.attribLocations.textureCoord, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D,texture);
   

    gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
}

function calcAngle() {
    if (g_angle1 < 120 || g_angle1 > 220) {
        step1 = null;
    }
    if(step1 == null){
        if (g_angle1 < 120  )
            step1 = g_angle_step
        else 
            step1 = -g_angle_step
    }
    g_angle1  = step1 + g_angle1;


    if (g_angle2 < 120 || g_angle2 > 220) {
        step2 = null;
    }
    if(step2 == null){
        if (g_angle2 < 120  )
            step2 = g_angle_step
        else 
            step2 = -g_angle_step
    }
    g_angle2  = step2 + g_angle2;

}
function drawFramebufferObject() {
    console.log("drawFramebufferObject() -> ",d.fbo);
  
    gl.viewport(0,0,OFFSCREEN_WIDTH,OFFSCREEN_HEIGHT);
    gl.clearColor(0.2,0.2,0.2,1.0);
    gl.bindFramebuffer(gl.FRAMEBUFFER,d.fbo);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    d.modelMatrix.setTranslate(0,0,0);
    drawBox([40,70,40],boxPos)

    // drawHead
    d.modelMatrix.translate(0,70,0);
    drawBox([20,20,20]);

    // drawarm
    pushMatrix(d.modelMatrix);   
    d.modelMatrix.translate(-25,-5,0).rotate(g_angle2,1,0,0);    
    drawBox([10,60,10]);
    d.modelMatrix = popMatrix()
    
    // // drawArm
    pushMatrix(d.modelMatrix)
    d.modelMatrix.translate(25,-5,0).rotate(g_angle1,1,0,0);
    drawBox([10,60,10]);
    d.modelMatrix = popMatrix()
    
    // //drawLeg
    pushMatrix(d.modelMatrix)
    d.modelMatrix.translate(-26,-65,0).rotate(g_angle1,1,0,0);
    drawBox([15,90,10]);
    d.modelMatrix = popMatrix()
    
    // //drawLeg
    pushMatrix(d.modelMatrix)
    d.modelMatrix.translate(26,-65,0).rotate(g_angle2,1,0,0);
    drawBox([15,90,10],[26,-55,0],30);
    d.modelMatrix = popMatrix()

    gl.bindFramebuffer(gl.FRAMEBUFFER,null);    
}

//画图
function drawView(index) {
    gl.viewport(0,0,gl.canvasWidth,gl.canvasHeight);      
    drawPlane(d.fbo.texture,index);
}

function drawScene() 
{
    console.log("drawScene() ->");
    // 画FramebufferObject
    // gl.viewport(0,0,gl.canvasWidth,gl.canvasHeight);
    // gl.clearColor(0.6,0.6,0.6,1.0);
    // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


    calcAngle();
    // 更新相机位置
    updateViewMatrix(1)
    drawFramebufferObject();    
    drawView(1)

    updateViewMatrix(2);
    drawFramebufferObject();    
    drawView(2)

    updateViewMatrix(3);
    drawFramebufferObject();    
    drawView(3)

    updateViewMatrix(4);
    drawFramebufferObject();    
    drawView(4)

}
